package cn.accp.mvc.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
public class FileUploadController {
	//单个文件上传
	@RequestMapping("/upload")
	public String upload(@RequestParam("file")CommonsMultipartFile file,HttpServletRequest request) throws IOException{
		//获取文件名
		//file.getOriginalFilename();
		//获取文件上传路径
		String path = request.getRealPath("/fileupload");
		InputStream inputStream = file.getInputStream();
		OutputStream outputStream = new FileOutputStream(new File(path,file.getOriginalFilename()));
		int len = 0;
		byte[] buffer = new byte[400];
		while ((len=inputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, len);
		}
		outputStream.close();
		inputStream.close();
		return "index.jsp";
	}
	//多个文件上传
	@RequestMapping("/moreupload")
	public String upload(@RequestParam("file")CommonsMultipartFile file[],HttpServletRequest request) throws IOException{
		String path = request.getRealPath("/fileupload");
		for (int i = 0; i < file.length; i++) {
			InputStream inputStream = file[i].getInputStream();
			OutputStream outputStream = new FileOutputStream(new File(path,file[i].getOriginalFilename()));
			int len = 0;
			byte[] buffer = new byte[400];
			while ((len=inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, len);
			}
			outputStream.close();
			inputStream.close();
		}
		return "index.jsp";
	}
}
